package com.shitou.springai1.user.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

// ConversationMemory.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ConversationMemory {
    private String sessionId;
    private List<ConversationTurn> history;
    private LocalDateTime createdAt;
    private LocalDateTime lastAccessed;
    private int maxTurns; // 最大对话轮数

    public ConversationMemory(String sessionId, int maxTurns) {
        this.sessionId = sessionId;
        this.history = new ArrayList<>();
        this.createdAt = LocalDateTime.now();
        this.lastAccessed = LocalDateTime.now();
        this.maxTurns = maxTurns;
    }

    public void addTurn(String role, String content) {
        this.history.add(new ConversationTurn(role, content, LocalDateTime.now()));
        this.lastAccessed = LocalDateTime.now();

        // 限制历史记录长度
        if (history.size() > maxTurns) {
            history.remove(0);
        }
    }

    public String getFormattedHistory() {
        if (history.isEmpty()) {
            return "";
        }

        StringBuilder sb = new StringBuilder();
        sb.append("之前的对话历史：\n\n");

        for (int i = Math.max(0, history.size() - 5); i < history.size(); i++) { // 最近5轮
            ConversationTurn turn = history.get(i);
            String speaker = turn.getRole().equals("user") ? "用户" : "小凯";
            sb.append(String.format("%s: %s\n", speaker, turn.getContent()));
        }

        return sb.toString();
    }
}

